<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  users
 */

class m_users_actions_block_front_ForgottenPasswordAction extends f_core_Action
{
	public function execute()
	{
		$formProvider = f_form_Provider::getInstance();
        $blockParams = $this->getBlockContext()->getParameters();
        $key = m_backoffice_services_BackOfficeService::getKey();

        if(!is_null($this->getRequestParameter("crypt")))
        {
            $crypt = $this->getRequestParameter("crypt");
            $valid = $this->getDocumentProvider()->loadDocuments("modules_users/activation")->whereIsEqual("url", $crypt)->retrieveFirstDocument();
            
            if(!is_null($valid))
            {
                $creationDate = f_date_Date::getInstance($valid->getCreationDate())->getTimeStamp();

                if(time() < $creationDate + intval($blockParams['validTime']))
                {
                    $formProvider->setDocumentName("password")
                             ->setModuleName("users")
                             ->setFormName("FormPassword");

                    $values = $formProvider->getParams();

                    if($formProvider->isSubmitted())
                    {
                        if($formProvider->isValid())
                        {
                            $newPwd = md5($values["formValues"]["password"].$key);
                            $user = $this->getDocumentProvider()->getByModelAndUniqueId("modules_users/user", $valid->getUser());
                            $user->setPassword($newPwd)->save(false);
                            $valid->delete();
                            $this->getController()->redirect("http://".HTTP_HOST);
                        }
                        else
                        {
                            $this->addToModel("errors", $formProvider->getErrors());
                        }
                    }
                }
                else
                {
                    $this->addToModel('late', true);
                }
            }
            else
            {
                $this->addToModel('noLink', true);
            }
            
            $this->addToModel("blockParams", $blockParams);
            return $this->setView('form');
        }

		$formProvider->setDocumentName("forgottenPassword")
		             ->setModuleName("users")
		             ->setFormName("FormForgottenPassword");

		$values = $formProvider->getParams();

		if($formProvider->isSubmitted())
		{
			if($formProvider->isValid())
			{
                $user = $this->getDocumentProvider()->loadDocuments("modules_users/user")->whereIsEqual("email", $values["formValues"]["email"])->retrieveFirstDocument();

                if(is_object($user))
                {
                    $crypt = md5($user->getEmail().$key);
                    $link = $this->getContext("currentPage")->getCompleteUrl() . "?crypt=" . $crypt;

                    $mailInfos = array("link" => $link);

                    $mail = f_mail_MailService::getInstance();
                    $mail->setSenderName("pagizer")
                         ->setSender("admin@pagizer.org")
                         ->setReceiver($user->getEmail())
                         ->setSubject($this->getLocale("users.form.forgottenPwdSubject"))
                         ->setContentFromTemplate("users", "forgottenPassword.html", array("values" => $mailInfos))
                         ->send();

                    if($mail)
                    {
                        m_users_documents_Activation::createNew()->setUrl($crypt)->setUser($user->getUniqueId())->save(false);
                        $this->addToModel("thx", true);
                    }
                    else
                    {
                        throw new Exception($this->getLocale("users.errors.emailSend"));
                    }
                }
			}
			else
			{
                $this->addToModel("errors", $formProvider->getErrors());
			}
		}
        
        $this->addToModel("blockParams", $blockParams);
		$this->setView('success');
	}	
	
	public function validate()
	{
		return true;
	}
	
	public function errorHandler()
	{
		$this->setView('error');
	}
}